package com.manage.modules.scoket;

import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * 自定义websocket服务端
 *
 * @author xu
 * 2021/8/20 15:03
 */
@ServerEndpoint(value = "/socket/{name}")
@Component
public class MySocketServer {


    //用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<MySocketServer> webSocketSet = new CopyOnWriteArraySet<>();

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;

    // 每个用户的唯一标识
    private String name;

    /**
     * 连接成功
     */
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "name") String name) {
        this.session = session;
        this.name = name;

        // 保证只有一个同名的socket
        webSocketSet.removeIf(item -> item.name.equals(name));

        // 加入新连接成功的session
        webSocketSet.add(this);
        // 发消息
        SocketSendMessageVo sendMessageVo = new SocketSendMessageVo();
        sendMessageVo.setMessage("恭喜您成功连接上WebSocket-->当前在线人数为：" + webSocketSet.size());
        sendMessageVo.setType("1");
        this.session.getAsyncRemote().sendText(JSON.toJSONString(sendMessageVo));
        System.out.println("name为：" + name + "的用户连接加入，连接人数为:" + webSocketSet.size());
    }

    /**
     * 连接断开
     */
    @OnClose
    public void onClose(Session session, @PathParam(value = "name") String name) {
        // 删除连接关闭的人数
        webSocketSet.remove(this);

        System.out.println("name为：" + name + "的用户连接断开，连接人数为:" + webSocketSet.size());
    }

    /**
     * 接收到客户端的消息
     */
    @OnMessage
    public void onMessage(String message, @PathParam(value = "name") String name) {
        System.out.println("name为：" + name + "的用户发生给服务端消息:" + message);
    }

    /**
     * 客户端发生错误
     */
    @OnError
    public void onError(@PathParam(value = "name") String name, Throwable error) {
        System.out.println("name为：" + name + "的用户发生错误");
        error.printStackTrace();
    }

    /**
     * 服务端发送消息给当前用户
     */
    public void sendMessage(SocketSendMessageVo sendMessageVo, String name) throws IOException {
        Session session = null;
        for (MySocketServer item : webSocketSet) {
            if (item.name.equals(name)) {
                session = item.session;
            }
        }
        // 为空就不发送
        if (session == null) {
            return;
        }
        session.getBasicRemote().sendText(JSON.toJSONString(sendMessageVo));
        System.out.println("给name为：" + name + "的用户发送消息：" + JSON.toJSONString(sendMessageVo));
    }

    /**
     * 群发消息
     */
    public void groupMessage(SocketSendMessageVo sendMessageVo) {
        for (MySocketServer item : webSocketSet) {
            //this.session.getBasicRemote().sendText(message);
            item.session.getAsyncRemote().sendText(JSON.toJSONString(sendMessageVo));//异步发送消息.
        }
    }
}
